package com.sun.search.controller;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sun.search.service.ItemSearchService;

@Controller
public class ItemSearchController {

	@Resource
	private ItemSearchService itemSearchService;
	
	@RequestMapping("/search.html")
	public String itemSearchIndex(@RequestParam(defaultValue="1")int page,@RequestParam(defaultValue="12")int rows,String q,Model retmodel){
		try {
			q = new String(q.getBytes("ISO-8859-1"),"utf-8");//消除GET请求中文乱码
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		Map<String, Object> tbItemSearchMap = null;
		try {
			tbItemSearchMap = itemSearchService.tbItemSearch(page, rows, q);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		retmodel.addAttribute("itemList", tbItemSearchMap.get("itemList"));
		retmodel.addAttribute("query", tbItemSearchMap.get("query"));
		retmodel.addAttribute("count", tbItemSearchMap.get("count"));
		retmodel.addAttribute("totalPages", tbItemSearchMap.get("totalPages"));
		retmodel.addAttribute("page", tbItemSearchMap.get("page"));
		
		return "search";
		
	}
	
	/**
	 * 按分类搜
	 * @param page
	 * @param rows
	 * @param catname 分类名称
	 * @param retmodel
	 * @return
	 */
	@RequestMapping("/search/cat.html")
	public String itemSearchByCat(@RequestParam(defaultValue="1")int page,@RequestParam(defaultValue="12")int rows,String catname,Model retmodel){
		//前台配置请求地址   规范的说  应该传入分类id  然后经过查询转化为catName  再进行查询
		try {
			catname = new String(catname.getBytes("ISO-8859-1"),"utf-8");//消除GET请求中文乱码
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		Map<String, Object> tbItemSearchMap = null;
		try {
			tbItemSearchMap = itemSearchService.tbItemSearch(page, rows, catname);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		retmodel.addAttribute("itemList", tbItemSearchMap.get("itemList"));
		retmodel.addAttribute("query", tbItemSearchMap.get("query"));
		retmodel.addAttribute("count", tbItemSearchMap.get("count"));
		retmodel.addAttribute("totalPages", tbItemSearchMap.get("totalPages"));
		retmodel.addAttribute("page", tbItemSearchMap.get("page"));
		return "search";
	}
	
}
